package com.mystudy.jcu.countDownLatch;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TODO: {@link CountDownLatch}测试
 * 第一种用法：将一系列可以并行化的任务进行执行
 *
 * @author acy
 * @since 2019/06/17 16:18
 */
public class CountDownLatchTest {
	private static final ExecutorService EXECUTORS = Executors.newFixedThreadPool(2);
	private static final CountDownLatch LATCH = new CountDownLatch(5);

	@Test
	public void test() throws Exception {
		int[] data = query();
		for (int i = 0; i < data.length; i++) {
			EXECUTORS.execute(new SimpleRunnable(data, i, LATCH));
		}
		LATCH.await();
		System.out.println("all job finish");
		EXECUTORS.shutdown();
	}

	private int[] query() {
		return new int[6];
	}

	static class SimpleRunnable implements Runnable {
		private final int[] data;
		private final int index;
		private final CountDownLatch latch;

		public SimpleRunnable(int[] data, int index, CountDownLatch latch) {
			this.data = data;
			this.index = index;
			this.latch = latch;
		}

		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("当前任务" + index + "执行完毕进行等待");
			LATCH.countDown();
		}
	}
}
